package com.zeyi.web.controller.file;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.IdUtil;
import com.zeyi.web.utils.ImageCompressUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("compress")
public class CompressController {

    @PreAuthorize("@ss.hasPermi('file:image:compress')")
    @PostMapping("image")
    public void uploadUserFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("desFileSize") long desFileSize,
            @RequestParam("accuracy") double accuracy,
            HttpServletResponse response) throws IOException {

        String extName = FileUtil.extName(file.getOriginalFilename());
        String path = IdUtil.simpleUUID() + CharUtil.DOT + extName;
        Path directory = Paths.get("compressFile");
        Files.createDirectories(directory);
        String srcPath = "tmpFile/" + path;
        String desPath = "compressFile/" + path;
        File tmpFile = new File(srcPath);
        FileUtils.copyInputStreamToFile(file.getInputStream(), tmpFile);

        ImageCompressUtils.compressPicForScale(srcPath, desPath, desFileSize, accuracy);

        BufferedImage image = ImageIO.read(Files.newInputStream(Paths.get(desPath)));

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, extName==null?"jpg":extName, out);


        Files.delete(Paths.get(srcPath));
        Files.delete(Paths.get(desPath));
    }
}

